package com.bw.culture.view

import android.app.Activity
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.bw.base.constants.RoutePath
import com.bw.common.view.BaseMvvmActivity
import com.bw.culture.R
import com.bw.culture.adapter.ImageAdapter
import com.bw.culture.adapter.ImagesAdapter
import com.bw.culture.databinding.ActivityAddNewsBinding
import com.bw.culture.entity.NewsEntity
import com.bw.culture.net.CultureViewModel
import com.bw.culture.onclick.ClickListener
import com.google.android.material.datepicker.MaterialDatePicker
import com.google.android.material.timepicker.MaterialTimePicker
import com.google.android.material.timepicker.TimeFormat
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import java.util.*
import kotlin.collections.ArrayList

/**
 * 智慧园区-文化管理
 * 发布新闻
 * 刘哲甫
 * 20250508
 */
@Route(path = RoutePath.PATH_ADD_CULTURE)
class AddNewsActivity : BaseMvvmActivity<ActivityAddNewsBinding , CultureViewModel>() {

    var newsEntity : NewsEntity = NewsEntity()

    private var imageUri : MutableList<String> = mutableListOf("+")

    private var uri:MutableList<Uri> = mutableListOf()
    private val images = mutableListOf<String>("+")

    private var imageAdapter:ImageAdapter= ImageAdapter(imageUri,uri)
    private val imgAdapter = ImagesAdapter()

    //设置最大长度
    val maxLength = 50

    //图片
//    private lateinit var imageView: ImageView
//    private lateinit var addImageText : TextView
    private var selectedImageUri : Uri? = null

    private var ps:Int = 0

    private val pickImageLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {resule ->
        if (resule.resultCode == RESULT_OK) {
            resule.data?.data?.let { uri ->
                selectedImageUri = uri
                showUploadedImage(uri)
            }
        }
    }

    override fun initView() {
        binding.topBer.ivBack.setOnClickListener { finish() }
        binding.topBer.tvTitle.text = "发布新闻"
        binding.topBer.ivEye.visibility = View.VISIBLE

        //初始化计数器显示
        binding.counterText.text = "0/$maxLength"

//        //布局图片列表展示样式
//        binding.images.adapter=imageAdapter
//        binding.images.layoutManager=GridLayoutManager(this,3)

        //文本变化监听器
        binding.etTitle.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                //变化前回调
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                //变化时回调
            }

            override fun afterTextChanged(p0: Editable?) {
                //变化后回调
                val currentLength = p0?.length ?: 0

                //更新计数器显示
                binding.counterText.text = "$currentLength/$maxLength"

                //限制最大长度
                if (currentLength > maxLength) {
                    val selectionStart = binding.etTitle.selectionStart
                    val selectionEnd = binding.etTitle.selectionEnd

                    //移除超出的部分
                    p0?.delete(maxLength , currentLength)

                    //调整光标位置
                    if (selectionStart > maxLength) {
                        binding.etTitle.setSelection(maxLength)
                    } else if (selectionStart == maxLength && selectionEnd > maxLength) {
                        binding.etTitle.setSelection(maxLength)
                    }
                }
            }
        })

        //新闻选择
        val newsTypes = arrayOf("园区新闻", "时政新闻", "娱乐新闻", "体育新闻", "财经新闻")
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, newsTypes)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.spinner.adapter = adapter

        //初始化显示
        binding.hintText.visibility = View.VISIBLE

        //监听选择事件，隐藏提示
        binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                binding.hintText.visibility = View.GONE
            }

            override fun onNothingSelected(p0: AdapterView<*>?) {

            }
        }

        //日期+时间选择器
        binding.dataTime.setOnClickListener {
            showMaterialDatePicker()
        }

//        //图片选择
//        val clickableViews = listOf(binding.images)
//        clickableViews.forEach { view ->
//            view.setOnClickListener {
//                openImagePicker()
//            }
//        }

        imageAdapter.setItemOnClickListener(object :ClickListener{
            override fun onClick(position: Int) {
                ps = position
                openImagePicker()
            }
        })
        imgAdapter.setOnItemClickListener { adapter, view, position ->

            if(position == adapter.data.size-1){
                PictureSelector.create(this,509).selectPicture()
            }
        }
        binding.images.adapter = imgAdapter
        binding.images.layoutManager = GridLayoutManager(this,3)

    }

    //日期
    private fun showMaterialDatePicker() {
        val datePicker = MaterialDatePicker.Builder.datePicker()
            .setTitleText("选择日期")
            .build()

        datePicker.addOnPositiveButtonClickListener { selection ->
            val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
            calendar.timeInMillis = selection
            val year = calendar.get(Calendar.YEAR)
            val month = calendar.get(Calendar.MONTH) + 1
            val day = calendar.get(Calendar.DAY_OF_MONTH)
            val selectedDate = "$year-${month.toString().padStart(2, '0')}-${day.toString().padStart(2,'0')}"

            showMaterialTimePicker(selectedDate)
        }
        datePicker.show(supportFragmentManager, "MATERIAL_DATE_PICKER")
    }

    //时间
    private fun showMaterialTimePicker(selectedDate : String) {
        val calendar = Calendar.getInstance()
        val timePicker = MaterialTimePicker.Builder()
            .setTitleText("选择时间 ")
            .setHour(calendar.get(Calendar.HOUR_OF_DAY))
            .setMinute(calendar.get(Calendar.MINUTE))
            .setTimeFormat(TimeFormat.CLOCK_24H)
            .build()

        timePicker.addOnPositiveButtonClickListener {
            val hour = timePicker.hour
            val minute = timePicker.minute
            val selectedTime = "${hour.toString().padStart(2,'0')}:${minute.toString().padStart(2,'0')}"
            val dateTime = "$selectedDate $selectedTime"
            binding.etPublishDate.text = dateTime
        }

        timePicker.show(supportFragmentManager, "MATERIAL_TIME_PICKER")
    }


    //图片选择
    private fun openImagePicker() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        pickImageLauncher.launch(intent)
    }

//10 && imageUri.size<10
    private fun showUploadedImage(imageUrl : Uri) {
        if(imageUri.size<10){
            if(imageUri.size==9){
                imageUrl.path?.let {
                    imageUri[imageUri.size-1]=it
                }
            }else{
                imageUrl.path?.let {
                    imageUri.add(0,it)
                }
            }
            uri.add(imageUrl)
        }
//        else{
            uri[ps]=imageUrl
//        }

        imageAdapter.notifyDataSetChanged()

        binding.textImages.visibility = android.view.View.GONE
//        Glide.with(this)
//            .load(imageUrl)
//            .into(binding.etImages)

    }


    override fun initData() {
        imgAdapter.data.addAll(images)
//        imgAdapter.notifyDataSetChanged()

        binding.sizeNum.setOnClickListener {
            ToastUtils.showLong(imgAdapter.data.size.toString())
        }

        binding.finish.setOnClickListener {
            newsEntity.title = binding.etTitle.text.toString()
            newsEntity.content = binding.etContent.text.toString()
            newsEntity.publishDate = binding.etPublishDate.text.toString()
            newsEntity.type = binding.hintText.text.toString()
            newsEntity.publisher = binding.etPublisher.text.toString()
            newsEntity.images=imageUri

            if (newsEntity.title == "" ||
                newsEntity.content == "" ||
                newsEntity.publishDate == "" ||
                newsEntity.type == "" ||
                newsEntity.publisher == "" ||
                newsEntity.images.size==0
            ) {
                ToastUtils.showLong("请选输入内容")
                return@setOnClickListener
            }

            vm.getAddNews(newsEntity)

        }

        vm.addNewsSuccess.observe(this) {
            ToastUtils.showLong("添加成功")
            finish()
        }

        vm.onFailed.observe(this) {
            ToastUtils.showLong("添加失败")
        }
    }
    var num : Int = 0
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==509&&resultCode== Activity.RESULT_OK){
            val extras = data?.extras
            val any = extras?.get(PictureSelector.PICTURE_RESULT) as PictureBean
            images.add(0,any.path)

            imgAdapter.data.add(num++,any.path)
            imgAdapter.notifyDataSetChanged()
        }

    }

}